<template>
  <div class="editor-view">
    <div class="back">
      <i class="el-icon-back"></i>
      <span>返回首页</span>
    </div>
    <div id="toolbar-container" class="toolbar"></div>
    <el-input v-model="title" placeholder="请输入新闻标题（5-30个字）" style="font-size:18px;"></el-input>
    <div id="text-container" class="text"></div>
    <el-form :model="form" label-width="100px" :rules="rules" ref="form">
      <el-form-item label="封面" prop="uploadImage" class="upload-img">
        <el-upload
          class="avatar-uploader"
          action="https://jsonplaceholder.typicode.com/posts/"
          :show-file-list="false"
          accept="image/*"
          :on-success="handleAvatarSuccess"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">发布</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import E from 'wangeditor'
export default {
  data() {
    const validateUploadImage = (rule, value, callback) => {
      if (this.imageUrl === '') {
        return callback(new Error('请上传封面'))
      } else {
        return callback()
      }
    }
    return {
      title: '',
      form: {},
      imageUrl: '',
      rules: {
        uploadImage: [
          {
            required: true,
            validator: validateUploadImage,
            trigger: 'change',
          },
        ],
      },
    }
  },
  mounted() {
    const editor = new E('#toolbar-container', '#text-container')
    editor.config.placeholder = '请输入新闻正文'
    editor.config.showMenuTooltips = true
    editor.config.menuTooltipPosition = 'down'
    editor.create()
  },
  methods: {
    handleAvatarSuccess(res, file) {
      console.log(file)
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          console.log('submit')
        } else {
          return false
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.editor-view {
  .back {
    margin: 10px 0;
    cursor: pointer;
  }
  .text {
    border: 1px solid #ccc;
    min-height: 400px;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .upload-img {
    display: flex;
    align-items: center;
    margin-top: 22px;
  }
}
</style>
